import http.server
import socketserver
import json
import os
import subprocess
import time
import urllib.parse
import psutil

# 配置文件路径 - 使用相对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SERVER_PATH = os.path.join(BASE_DIR, 'DayZServer')
SERVER_CONFIG_PATH = os.path.join(SERVER_PATH, 'serverDZ.cfg')
SERVER_EXECUTABLE_PATH = os.path.join(SERVER_PATH, 'DayZServer_x64.exe')

# 服务器进程 - 模块级变量
server_process = None

# 服务器控制功能相关代码

# 解析配置文件
def parse_config_file():
    try:
        if not os.path.exists(SERVER_CONFIG_PATH):
            # 如果配置文件不存在，创建默认配置
            default_config = {
                'hostname': 'DayZ Server',
                'password': '',
                'passwordAdmin': '',
                'description': 'DayZ Server',
                'enableWhitelist': 0,
                'maxPlayers': 60,
                'verifySignatures': 2,
                'forceSameBuild': 1,
                'disableVoN': 0,
                'vonCodecQuality': 20,
                'shardId': '123abc',
                'disable3rdPerson': 0,
                'disableCrosshair': 0,
                'disablePersonalLight': 1,
                'lightingConfig': 0,
                'serverTime': 'SystemTime',
                'serverTimeAcceleration': 12,
                'serverNightTimeAcceleration': 1,
                'serverTimePersistent': 0,
                'guaranteedUpdates': 1,
                'loginQueueConcurrentPlayers': 5,
                'loginQueueMaxPlayers': 500,
                'instanceId': 1,
                'storageAutoFix': 1,
                'missionTemplate': 'dayzOffline.chernarusplus',
                # 服务器路径配置
                'serverPath': 'DayZServer',
                'serverExe': 'DayZServer_x64.exe',
                'serverPort': 2302,
                'serverCfgPath': 'serverDZ.cfg',
                  'profilesPath': 'profiles',
                  'battleyePath': 'battleye',
                'rconPassword': 'rcon',
                # 服务器启动参数
                'doLogs': True,
                'adminLog': True,
                'netLog': False,
                'freezeCheck': True,
                'filePatching': False,
                'scriptDebug': False,
                'scrAllowFileWrite': True,
                'limitFPS': -1,
                'cpuCount': -1,
                'inputPreset': 'Default',
                # dayzsetting.xml配置
                'dayzsettingpcmaxcores': 2,
                'dayzsettingreservedcores': 1,
                'dayzsettingglobalqueue': 4096,
                'dayzsettingthreadqueue': 1024,
                # 其他配置
                'serverLaunchParams': [],
                'serverProcessPollIntervall': 30000,
                'disableStuckCheck': False,
                'disableServerMonitoring': False,
                'lockServerRestart': False,
                'disableServerLockLogs': False,
                'experimentalServer': False,
                # 备份配置
                'backupPath': 'backups',
                'backupMaxAge': 7
            }
            return default_config
        
        with open(SERVER_CONFIG_PATH, 'r', encoding='utf-8') as f:
            config_content = f.read()
        
        config = {}
        # 解析基本配置
        import re
        matches = re.findall(r'(\w+)\s*=\s*(?:"([^"]+)"|(\d+(?:\.\d+)?));', config_content)
        for match in matches:
            key, string_value, int_value = match
            if int_value:
                config[key] = int(int_value)
            elif string_value is not None:
                config[key] = string_value
        
        # 解析任务模板
        mission_match = re.search(r'template\s*=\s*"([^"]+)"', config_content)
        if mission_match:
            config['missionTemplate'] = mission_match.group(1)
        
        # 从JSON配置文件加载额外参数
        json_config_path = os.path.join(SERVER_PATH, 'server_config.json')
        if os.path.exists(json_config_path):
            try:
                import json
                with open(json_config_path, 'r', encoding='utf-8') as json_file:
                    json_config = json.load(json_file)
                    # 更新配置字典，保留原有参数
                    for key, value in json_config.items():
                        if key not in config:
                            config[key] = value
            except Exception as e:
                print(f"Failed to load JSON config file: {str(e)}")
        
        return config
    except Exception as e:
        raise Exception(f'Failed to parse config file: {str(e)}')

def validate_config(config):
    """验证服务器配置的有效性"""
    errors = []
    
    # 验证必要字段
    required_fields = ['hostname', 'maxPlayers']
    for field in required_fields:
        if field not in config:
            errors.append(f'缺少必要字段: {field}')
    
    # 验证端口范围
    if 'serverPort' in config:
        port = config['serverPort']
        if not isinstance(port, int) or port < 1024 or port > 65535:
            errors.append('服务器端口必须是1024-65535之间的整数')
    
    # 验证玩家数量
    if 'maxPlayers' in config:
        players = config['maxPlayers']
        if not isinstance(players, int) or players < 1 or players > 100:
            errors.append('玩家数量必须是1-100之间的整数')
    
    # 验证服务器名称长度
    if 'hostname' in config and len(config['hostname']) > 100:
        errors.append('服务器名称长度不能超过100个字符')
    
    # 验证BattlEye设置
    if 'BattlEye' in config and config['BattlEye'] not in [0, 1]:
        errors.append('BattlEye设置必须是0或1')
    
    return errors

# 保存配置文件
def save_config_file(config):
    try:
        # 验证配置
        validation_errors = validate_config(config)
        if validation_errors:
            return False, validation_errors
    except Exception as e:
        return False, [f'配置验证失败: {str(e)}']
    
    try:
        content = []
        
        # 基本配置
        content.append(f'hostname = "{config.get("hostname", "DayZ Server")}";  // Server name')
        content.append(f'password = "{config.get("password", "")}";              // Password to connect to the server')
        content.append(f'passwordAdmin = "{config.get("passwordAdmin", "")}";         // Password to become a server admin')
        content.append('')
        content.append(f'description = "{config.get("description", "")}";\t\t// Description of the server. Gets displayed to users in client server browser.')
        content.append('')
        content.append(f'enableWhitelist = {config.get("enableWhitelist", 0)};        // Enable/disable whitelist (value 0-1)')
        content.append(' ')
        content.append(f'maxPlayers = {config.get("maxPlayers", 60)};            // Maximum amount of players')
        content.append(' ')
        content.append(f'verifySignatures = {config.get("verifySignatures", 2)};       // Verifies .pbos against .bisign files. (only 2 is supported)')
        content.append(f'forceSameBuild = {config.get("forceSameBuild", 1)};         // When enabled, the server will allow the connection only to clients with same the .exe revision as the server (value 0-1)')
        content.append(' ')
        content.append(f'disableVoN = {config.get("disableVoN", 0)};             // Enable/disable voice over network (value 0-1)')
        content.append(f'vonCodecQuality = {config.get("vonCodecQuality", 20)};       // Voice over network codec quality, the higher the better (values 0-30)')
        content.append(' ')
        content.append(f'shardId = "{config.get("shardId", "123abc")}";\t\t// Six alphanumeric characters for Private server')
        content.append(f'disable3rdPerson={config.get("disable3rdPerson", 0)};         // Toggles the 3rd person view for players (value 0-1)')
        content.append(f'disableCrosshair={config.get("disableCrosshair", 0)};         // Toggles the cross-hair (value 0-1)')
        content.append('')
        content.append(f'disablePersonalLight = {config.get("disablePersonalLight", 1)};   // Disables personal light for all clients connected to server')
        content.append(f'lightingConfig = {config.get("lightingConfig", 0)};         // 0 for brighter night setup, 1 for darker night setup')
        content.append(' ')
        content.append(f'serverTime="{config.get("serverTime", "SystemTime")}";    // Initial in-game time of the server. "SystemTime" means the local time of the machine. Another possibility is to set the time to some value in "YYYY/MM/DD/HH/MM" format, f.e. "2015/4/8/17/23" .')
        content.append(f'serverTimeAcceleration={config.get("serverTimeAcceleration", 12)};  // Accelerated Time (value 0-24)// This is a time multiplier for in-game time. In this case, the time would move 24 times faster than normal, so an entire day would pass in one hour.')
        content.append(f'serverNightTimeAcceleration={config.get("serverNightTimeAcceleration", 1)};  // Accelerated Nigh Time - The numerical value being a multiplier (0.1-64) and also multiplied by serverTimeAcceleration value. Thus, in case it is set to 4 and serverTimeAcceleration is set to 2, night time would move 8 times faster than normal. An entire night would pass in 3 hours.')
        content.append(f'serverTimePersistent={config.get("serverTimePersistent", 0)};     // Persistent Time (value 0-1)// The actual server time is saved to storage, so when active, the next server start will use the saved time value.')
        content.append(' ')
        content.append(f'guaranteedUpdates={config.get("guaranteedUpdates", 1)};        // Communication protocol used with game server (use only number 1)')
        content.append(' ')
        content.append(f'loginQueueConcurrentPlayers={config.get("loginQueueConcurrentPlayers", 5)};  // The number of players concurrently processed during the login process. Should prevent massive performance drop during connection when a lot of people are connecting at the same time.')
        content.append(f'loginQueueMaxPlayers={config.get("loginQueueMaxPlayers", 500)};       // The maximum number of players that can wait in login queue')
        content.append(' ')
        content.append(f'instanceId = {config.get("instanceId", 1)};             // DayZ server instance id, to identify the number of instances per box and their storage folders with persistence files')
        content.append('')
        content.append(f'storageAutoFix = {config.get("storageAutoFix", 1)};         // Checks if the persistence files are corrupted and replaces corrupted ones with empty ones (value 0-1)')
        content.append('')
        
        # 任务配置
        content.append('class Missions')
        content.append('{')
        content.append('    class DayZ')
        content.append('    {')
        content.append(f'        template="{config.get("missionTemplate", "dayzOffline.chernarusplus")}"; // Mission to load on server startup. <MissionName>.<TerrainName>')
        content.append('					      // Vanilla mission: dayzOffline.chernarusplus')
        content.append('					      // DLC mission: dayzOffline.enoch')
        content.append('    }')
        content.append('}')
        
        # 添加BattlEye配置
        content.append('')
        content.append('// BattlEye Configuration')
        content.append('BattlEye = 0; // BE反作弊功能（0=禁用, 1=启用）')
        
        # 写入配置文件
        with open(SERVER_CONFIG_PATH, 'w', encoding='utf-8') as f:
            f.write('\n'.join(content))
        
        # 创建或更新JSON配置文件以存储所有参数
        json_config_path = os.path.join(SERVER_PATH, 'server_config.json')
        json_config = {
            # 服务器路径配置
            'serverPath': config.get('serverPath', 'DayZServer'),
            'serverExe': config.get('serverExe', 'DayZServer_x64.exe'),
            'serverPort': config.get('serverPort', 2302),
            'serverCfgPath': config.get('serverCfgPath', 'serverDZ.cfg'),
            'profilesPath': config.get('profilesPath', 'profiles'),
            'battleyePath': config.get('battleyePath', 'battleye'),
            'rconPassword': config.get('rconPassword', 'rcon'),
            # 服务器启动参数
            'doLogs': config.get('doLogs', True),
            'adminLog': config.get('adminLog', True),
            'netLog': config.get('netLog', False),
            'freezeCheck': config.get('freezeCheck', True),
            'filePatching': config.get('filePatching', False),
            'scriptDebug': config.get('scriptDebug', False),
            'scrAllowFileWrite': config.get('scrAllowFileWrite', True),
            'limitFPS': config.get('limitFPS', -1),
            'cpuCount': config.get('cpuCount', -1),
            'inputPreset': config.get('inputPreset', 'Default'),
            # dayzsetting.xml配置
            'dayzsettingpcmaxcores': config.get('dayzsettingpcmaxcores', 2),
            'dayzsettingreservedcores': config.get('dayzsettingreservedcores', 1),
            'dayzsettingglobalqueue': config.get('dayzsettingglobalqueue', 4096),
            'dayzsettingthreadqueue': config.get('dayzsettingthreadqueue', 1024),
            # 其他配置
            'serverLaunchParams': config.get('serverLaunchParams', []),
            'serverProcessPollIntervall': config.get('serverProcessPollIntervall', 30000),
            'disableStuckCheck': config.get('disableStuckCheck', False),
            'disableServerMonitoring': config.get('disableServerMonitoring', False),
            'lockServerRestart': config.get('lockServerRestart', False),
            'disableServerLockLogs': config.get('disableServerLockLogs', False),
            'experimentalServer': config.get('experimentalServer', False),
            # 备份配置
            'backupPath': config.get('backupPath', 'backups'),
            'backupMaxAge': config.get('backupMaxAge', 7)
        }
        
        import json
        with open(json_config_path, 'w', encoding='utf-8') as json_file:
            json.dump(json_config, json_file, ensure_ascii=False, indent=2)
        
        # 更新dayzsetting.xml文件
        update_dayzsetting_xml(json_config)
        
        return True, []
    except Exception as e:
        print(f"保存配置文件失败: {e}")
        return False, [f'保存配置失败: {str(e)}']

# 服务器控制函数
def start_server():
    global server_process
    # 检查服务器是否已经在运行
    if server_process is not None and server_process.poll() is None:
        print("Server is already running")
        return False
    
    try:
        # 读取配置文件
        config = parse_config_file()
        
        # 检查可执行文件是否存在
        if not os.path.exists(SERVER_EXECUTABLE_PATH):
            print(f"Error: Server executable not found at {SERVER_EXECUTABLE_PATH}")
            raise Exception(f"服务器可执行文件不存在: {SERVER_EXECUTABLE_PATH}")
        
        # 构建启动参数列表
        args = [SERVER_EXECUTABLE_PATH]
        
        # 基本配置参数 - 使用相对路径
        args.append(f'-config={config.get("serverCfgPath", "serverDZ.cfg")}')
        args.append(f'-port={config.get("serverPort", 2302)}')
        
        # RCon配置
        if config.get('rconPassword'):
            args.append(f'-rconPassword={config["rconPassword"]}')
            args.append('-rconPort=2306')  # 默认RCon端口
        
        # 日志相关参数
        if config.get('doLogs', True):
            args.append('-doLogs')
        if config.get('adminLog', True):
            args.append('-adminLog')
        if config.get('netLog', False):
            args.append('-netLog')
        
        # 其他功能参数
        if config.get('freezeCheck', True):
            args.append('-freezeCheck')
        if config.get('filePatching', False):
            args.append('-filePatching')
        if config.get('scriptDebug', False):
            args.append('-scriptDebug')
        if config.get('scrAllowFileWrite', True):
            args.append('-scrAllowFileWrite')
        
        # 性能相关参数
        if config.get('limitFPS', -1) > 0:
            args.append(f'-limitFPS={config["limitFPS"]}')
        if config.get('cpuCount', -1) > 0:
            args.append(f'-cpuCount={config["cpuCount"]}')
        
        # 配置文件路径参数 - 使用相对路径
        profiles_path = config.get('profilesPath', 'profiles')
        args.append(f'-profiles="{profiles_path}"')
        
        # BattlEye配置 - 使用相对路径
        battleye_path = config.get('battleyePath', 'battleye')
        args.append(f'-bepath="{battleye_path}"')
        
        # 任务模板配置 - 使用相对路径
        mission_template = config.get("missionTemplate", "dayzOffline.chernarusplus")
        args.append(f'-mission="mpmissions\\{mission_template}"')
        
        # 添加用户自定义启动参数
        if 'serverLaunchParams' in config and isinstance(config['serverLaunchParams'], list):
            args.extend(config['serverLaunchParams'])
        
        # 移除了inputPreset="Default"参数，按照用户要求
        
        print(f"Starting server with arguments: {args}")
        
        # 启动服务器进程，添加creationflags参数以显示控制台窗口
        import subprocess
        CREATE_NEW_CONSOLE = 0x00000010  # 创建新控制台窗口的标志
        server_process = subprocess.Popen(
            args,
            cwd=SERVER_PATH,
            shell=True,
            stdout=None,  # 不捕获stdout，允许显示在控制台窗口
            stderr=None,  # 不捕获stderr，允许显示在控制台窗口
            text=True,
            creationflags=CREATE_NEW_CONSOLE  # 在Windows上创建新的控制台窗口
        )
        
        # 立即读取一些输出，检查是否有立即失败的情况
        # 给服务器1秒时间来输出任何初始错误
        time.sleep(1)
        
        # 检查进程是否已经退出
        if server_process.poll() is not None:
            stdout, stderr = server_process.communicate()
            error_msg = f"服务器启动失败，进程立即退出。退出码: {server_process.returncode}\nSTDOUT: {stdout}\nSTDERR: {stderr}"
            print(error_msg)
            raise Exception(error_msg)
        
        # 如果配置了dayzsetting.xml相关参数，更新dayzsetting.xml文件
        update_dayzsetting_xml(config)
        
        print("Server started successfully")
        return True
    except Exception as e:
        # 捕获所有异常并记录详细信息
        print(f"Error starting server: {str(e)}")
        # 确保server_process设置为None，以便可以再次尝试启动
        server_process = None
        # 重新抛出异常，让API层能够捕获并返回错误信息
        raise
    return False

def update_dayzsetting_xml(config):
    """更新dayzsetting.xml文件中的配置参数"""
    try:
        dayzsetting_path = os.path.join(SERVER_PATH, 'dayzsetting.xml')
        if not os.path.exists(dayzsetting_path):
            # 创建默认的dayzsetting.xml文件
            default_content = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dayzSettings>
    <cpu>
        <maxcores>2</maxcores>
        <reservedcores>1</reservedcores>
    </cpu>
    <memory>
        <globalqueue>4096</globalqueue>
        <threadqueue>1024</threadqueue>
    </memory>
</dayzSettings>'''
            with open(dayzsetting_path, 'w', encoding='utf-8') as f:
                f.write(default_content)
        
        # 读取现有文件
        with open(dayzsetting_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 更新参数
        import re
        content = re.sub(r'<maxcores>\d+</maxcores>', 
                        f'<maxcores>{config.get("dayzsettingpcmaxcores", 2)}</maxcores>', 
                        content)
        content = re.sub(r'<reservedcores>\d+</reservedcores>', 
                        f'<reservedcores>{config.get("dayzsettingreservedcores", 1)}</reservedcores>', 
                        content)
        content = re.sub(r'<globalqueue>\d+</globalqueue>', 
                        f'<globalqueue>{config.get("dayzsettingglobalqueue", 4096)}</globalqueue>', 
                        content)
        content = re.sub(r'<threadqueue>\d+</threadqueue>', 
                        f'<threadqueue>{config.get("dayzsettingthreadqueue", 1024)}</threadqueue>', 
                        content)
        
        # 写回文件
        with open(dayzsetting_path, 'w', encoding='utf-8') as f:
            f.write(content)
            
    except Exception as e:
        print(f"Failed to update dayzsetting.xml: {str(e)}")

def stop_server():
    global server_process
    if server_process is not None and server_process.poll() is None:
        subprocess.run(f'taskkill /F /T /PID {server_process.pid}', shell=True)
        server_process = None
        return True
    return False

def pause_server():
    global server_process
    if server_process is not None and server_process.poll() is None:
        try:
            # 在Windows上，我们可以使用PowerShell的Suspend-Process命令来暂停进程
            subprocess.run(['powershell', f'Suspend-Process -Id {server_process.pid}'], shell=True, check=True)
            return True
        except Exception as e:
            print(f"Error pausing server: {str(e)}")
            return False
    return False

def resume_server():
    global server_process
    if server_process is not None and server_process.poll() is None:
        try:
            # 在Windows上，我们可以使用PowerShell的Resume-Process命令来恢复进程
            subprocess.run(['powershell', f'Resume-Process -Id {server_process.pid}'], shell=True, check=True)
            return True
        except Exception as e:
            print(f"Error resuming server: {str(e)}")
            return False
    return False

def get_server_status():
    global server_process
    if server_process is None or server_process.poll() is not None:
        return {'running': False, 'paused': False}
    
    try:
        # 尝试检查进程是否被暂停
        # 使用PowerShell查询进程状态
        result = subprocess.run(
            ['powershell', f'Get-Process -Id {server_process.pid} | Select-Object -ExpandProperty Responding'],
            capture_output=True,
            text=True,
            shell=True
        )
        
        # 如果命令成功执行且输出为False，则进程被暂停
        if result.returncode == 0:
            output = result.stdout.strip().lower()
            # 如果进程没有响应，通常意味着它被暂停了
            paused = output == 'false'
            return {'running': True, 'paused': paused}
    except Exception as e:
        print(f"Error checking process status: {str(e)}")
    
    # 默认情况：进程在运行但无法确定是否暂停
    return {'running': True, 'paused': False}

def get_server_logs(lines=100):
    """获取服务器日志的最后几行"""
    # 定义可能的日志文件路径
    log_dir = os.path.join(SERVER_PATH, 'logs')
    logs = []
    
    try:
        # 检查日志目录是否存在
        if os.path.exists(log_dir) and os.path.isdir(log_dir):
            # 获取最新的日志文件
            log_files = [f for f in os.listdir(log_dir) if f.endswith('.log')]
            if log_files:
                # 按修改时间排序，获取最新的
                log_files.sort(key=lambda x: os.path.getmtime(os.path.join(log_dir, x)), reverse=True)
                latest_log = log_files[0]
                log_path = os.path.join(log_dir, latest_log)
                
                # 读取最后几行
                with open(log_path, 'r', encoding='utf-8', errors='ignore') as f:
                    logs = f.readlines()[-lines:]
                
                # 转换为字符串并返回
                return {'success': True, 'logs': ''.join(logs), 'file': latest_log}
            else:
                return {'success': True, 'logs': '没有找到日志文件', 'file': None}
        else:
            # 如果日志目录不存在，尝试从进程的stdout读取
            global server_process
            if server_process is not None and server_process.poll() is None:
                # 注意：这个实现有限制，因为我们在启动进程时捕获了stdout但没有持续读取
                return {'success': True, 'logs': '无法读取进程实时输出，请检查日志文件目录', 'file': None}
            return {'success': True, 'logs': '服务器未运行或日志目录不存在', 'file': None}
    except Exception as e:
        return {'success': False, 'message': f'读取日志失败: {str(e)}'}

# 简单的HTTP处理类
class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    # 处理GET请求
    def do_GET(self):
        # 健康检查
        if self.path == '/api/health':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = {'success': True, 'message': 'Backend service running normally'}
            self.wfile.write(json.dumps(response).encode())
        
        # 获取服务器配置
        elif self.path == '/api/config':
            try:
                config = parse_config_file()
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': True, 'data': config}
                self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to read config', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        

        
        # 获取服务器状态
        elif self.path == '/api/server/status':
            try:
                status = get_server_status()
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': True, 'data': status}
                self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to get server status', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 获取任务模板列表
        elif self.path == '/api/mission-templates':
            try:
                mission_dir = os.path.join(BASE_DIR, 'DayZServer', 'mpmissions')
                templates = []
                
                if os.path.exists(mission_dir):
                    # 获取所有子目录作为任务模板
                    for item in os.listdir(mission_dir):
                        item_path = os.path.join(mission_dir, item)
                        if os.path.isdir(item_path):
                            templates.append(item)
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': True, 'templates': templates}
                self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to get mission templates', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        

        
        # 提供前端文件
        else:
            # 尝试从dist目录提供已构建的静态文件
            file_path = self.path[1:] if self.path != '/' else 'index.html'
            file_path = os.path.join(BASE_DIR, 'frontend', 'dist', file_path)
            
            # 安全检查：确保文件在允许的目录内
            if not os.path.abspath(file_path).startswith(os.path.join(BASE_DIR, 'frontend', 'dist')):
                self.send_response(403)
                self.end_headers()
                return
            
            try:
                # 如果文件存在，提供它
                if os.path.exists(file_path) and os.path.isfile(file_path):
                    self.send_response(200)
                    # 设置适当的MIME类型
                    if file_path.endswith('.html'):
                        self.send_header('Content-Type', 'text/html')
                    elif file_path.endswith('.css'):
                        self.send_header('Content-Type', 'text/css')
                    elif file_path.endswith('.js'):
                        self.send_header('Content-Type', 'application/javascript')
                    elif file_path.endswith('.json'):
                        self.send_header('Content-Type', 'application/json')
                    else:
                        # 为其他类型设置默认MIME类型
                        self.send_header('Content-Type', 'application/octet-stream')
                    
                    self.end_headers()
                    with open(file_path, 'rb') as f:
                        self.wfile.write(f.read())
                else:
                    # 如果请求的是API端点但未找到，返回404
                    if self.path.startswith('/api/'):
                        self.send_response(404)
                        self.send_header('Content-Type', 'application/json')
                        self.end_headers()
                        response = {'success': False, 'message': 'API endpoint not found'}
                        self.wfile.write(json.dumps(response).encode())
                    else:
                        # 对于其他请求，尝试提供index.html用于单页应用路由
                        index_path = os.path.join(BASE_DIR, 'frontend', 'dist', 'index.html')
                        if os.path.exists(index_path):
                            self.send_response(200)
                            self.send_header('Content-Type', 'text/html')
                            self.end_headers()
                            with open(index_path, 'rb') as f:
                                self.wfile.write(f.read())
                        else:
                            self.send_response(404)
                            self.end_headers()
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to serve file', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
    
    # 处理POST请求
    def do_POST(self):
        # 保存服务器配置
        if self.path == '/api/config':
            try:
                content_length = int(self.headers['Content-Length'])
                post_data = self.rfile.read(content_length).decode('utf-8')
                
                # 验证JSON格式
                try:
                    config_data = json.loads(post_data)
                    if not isinstance(config_data, dict):
                        self.send_response(400)
                        self.send_header('Content-Type', 'application/json')
                        self.end_headers()
                        response = {'success': False, 'message': '配置数据必须是对象格式'}
                        self.wfile.write(json.dumps(response).encode())
                        return
                except json.JSONDecodeError as e:
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': '无效的JSON格式', 'error': str(e)}
                    self.wfile.write(json.dumps(response).encode())
                    return
                
                # 保存配置
                success, errors = save_config_file(config_data)
                
                if success:
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': True, 'message': '配置保存成功'}
                    self.wfile.write(json.dumps(response).encode())
                else:
                    # 配置验证失败，返回400错误
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': '配置验证失败', 'errors': errors}
                    self.wfile.write(json.dumps(response).encode())
                    
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': '保存配置时发生服务器错误', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 启动服务器
        elif self.path == '/api/server/start':
            try:
                if start_server():
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': True, 'message': 'Server started successfully'}
                    self.wfile.write(json.dumps(response).encode())
                else:
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': 'Server is already running'}
                    self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to start server', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 停止服务器
        elif self.path == '/api/server/stop':
            try:
                if stop_server():
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': True, 'message': 'Server stopped'}
                    self.wfile.write(json.dumps(response).encode())
                else:
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': 'Server is not running'}
                    self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to stop server', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 暂停服务器
        elif self.path == '/api/server/pause':
            try:
                if pause_server():
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': True, 'message': 'Server paused'}
                    self.wfile.write(json.dumps(response).encode())
                else:
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': 'Server is not running or could not be paused'}
                    self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to pause server', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 恢复服务器
        elif self.path == '/api/server/resume':
            try:
                if resume_server():
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': True, 'message': 'Server resumed'}
                    self.wfile.write(json.dumps(response).encode())
                else:
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': 'Server is not running or could not be resumed'}
                    self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to resume server', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 获取服务器日志
        elif self.path.startswith('/api/server/logs'):
            try:
                # 从URL参数中获取lines参数
                import urllib.parse
                parsed_url = urllib.parse.urlparse(self.path)
                query_params = urllib.parse.parse_qs(parsed_url.query)
                lines = int(query_params.get('lines', [100])[0])
                
                logs_result = get_server_logs(lines)
                if logs_result['success']:
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': True, 'data': logs_result}
                    self.wfile.write(json.dumps(response).encode())
                else:
                    self.send_response(500)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    response = {'success': False, 'message': logs_result.get('message', 'Failed to get logs')}
                    self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to get server logs', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 获取任务模板列表
        elif self.path == '/api/mission-templates':
            try:
                mission_dir = os.path.join(BASE_DIR, 'DayZServer', 'mpmissions')
                templates = []
                
                if os.path.exists(mission_dir):
                    # 获取所有子目录作为任务模板
                    for item in os.listdir(mission_dir):
                        item_path = os.path.join(mission_dir, item)
                        if os.path.isdir(item_path):
                            templates.append(item)
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': True, 'templates': templates}
                self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = {'success': False, 'message': 'Failed to get mission templates', 'error': str(e)}
                self.wfile.write(json.dumps(response).encode())
        
        # 模拟获取公网IP（为了兼容前端）
        elif self.path == '/api/stun/public-ip':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = {'success': True, 'public_ip': '127.0.0.1'}
            self.wfile.write(json.dumps(response).encode())
        
        else:
            self.send_response(404)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = {'success': False, 'message': 'API endpoint not found'}
            self.wfile.write(json.dumps(response).encode())
    
    # 添加CORS支持
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()
    
    # 处理OPTIONS请求
    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

# 启动服务器
if __name__ == '__main__':
    PORT = 5000
    Handler = SimpleHTTPRequestHandler
    
    with socketserver.TCPServer(("localhost", PORT), Handler) as httpd:
        print(f"DayZ Server Manager Backend running on http://localhost:{PORT}")
        print("Available endpoints:")
        print("- GET /api/health          - Health check")
        print("- GET /api/config          - Get server configuration")
        print("- POST /api/config         - Save server configuration")
        print("- GET /api/server/status   - Get server status")
        print("- POST /api/server/start   - Start the server")
        print("- POST /api/server/stop    - Stop the server")
        print("- POST /api/server/pause   - Pause the server")
        print("- POST /api/server/resume  - Resume the server")
        print("- GET /api/server/logs     - Get server logs (with optional ?lines=100)")
        print("- GET /api/mission-templates - Get mission templates")

        print("\nPress Ctrl+C to stop the server...")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nBackend server stopped")

            # 确保在退出时停止DayZ服务器
            if get_server_status():
                print("Stopping DayZ server...")
                stop_server()